package com.etooling.framework.utils;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.etooling.framework.entity.AttachFile;
import com.etooling.framework.svo.ReplyObj;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Predicate;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * @author 周志荣
 * @title: WebUtils
 * @description: 用于web的基本处理工具类
 * @date 2020/12/18 18:17
 */
public class WebUtils {
    public static final String M_LOGIN_USER_KEY = "M_LOGIN_USER_KEY";
    public static final String LOGIN_USER_KEY = "LOGIN_USER_KEY";
    public static final String LOGIN_ORG_ID_KEY = "LOGIN_ORG_ID_KEY";
    public static final String LOGIN_COMPANY_ID_KEY = "LOGIN_COMPANY_ID_KEY";

    /**
     * 　　* @description: 判断字符串是否为空
     * 　　* @param
     * 　　* @return
     * 　　* @throws
     * 　　* @author 周志荣
     * 　　* @date 2020/12/18 18:18
     */
    public static boolean checkStr(String str) {
        if (str != null && !"".equals(str.trim()) && !"undefined".equals(str.trim()) && !"null".equals(str.trim())) {
            return true;
        }
        return false;
    }


    private static boolean createDirectory(String folder) {
        File dir = new File(folder);
        if (dir.exists()) {
            return true;
        } else {
            return dir.mkdirs();
        }
    }

    /**
     * 　　* @description: 返回操作成功，连带对象
     * 　　* @param
     * 　　* @return
     * 　　* @throws
     * 　　* @author 周志荣
     * 　　* @date 2020/12/18 18:18
     */
    public static ReplyObj flushObjSuccess(Object value) {
        ReplyObj r = new ReplyObj();
        return r.setData(value);
    }


    public static String getMd5Str(String initValue) {
        String retVal = initValue;
        byte[] pass_bytes;
        try {

            pass_bytes = Digest.getMessageDigest(initValue, Digest.MD5);
            retVal = Digest.byte2hex(pass_bytes);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return retVal;
    }


    public static ReplyObj flushSuccess(Object value) {
        return new ReplyObj(value);
    }

    public static ReplyObj flushSuccess() {
        return new ReplyObj();
    }

    public static ReplyObj flushSuccess(String msg) {
        return new ReplyObj().setMsg(msg);
    }

    public static ReplyObj flushFailure(String msg) {
        ReplyObj r = new ReplyObj();
        r.setCode(503);
        r.setMsg(msg);
        return r;

    }

    public static ReplyObj fileUpLoadSuccess(AttachFile file, Object data) {
        HashMap map = new HashMap();
        map.put("fileId", file.getId());
        map.put("url", file.getWebPath());
        map.put("fileName", file.getName());
        map.put("status", "done");
        map.put("data", data);
        return flushObjSuccess(map);

    }

    public <S> Specification<S> createSpecification(List<Predicate> conditions) {
        Specification<S> specification = (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();

            for (Predicate condition : conditions) {
                predicates.add(condition);
            }
            Predicate[] pre = new Predicate[predicates.size()];
            Predicate preAnd = cb.and(predicates.toArray(pre));
            return query.where(preAnd).getRestriction();
        };
        return specification;
    }


    public static String setSessionValue(String token, String key, String value) {
        token = JwtUtil.setSession(token, key, value);
        return token;
    }


    public static String getSessionValue(HttpServletRequest request, String key) {
        String token = request.getHeader("token");
        if (checkStr(request.getHeader("companyId"))) {
            token = JwtUtil.setSession(token, WebUtils.LOGIN_COMPANY_ID_KEY, request.getHeader("companyId"));
        }
//        System.out.println(token);
        String sessionValues = JwtUtil.getTokenInfo(token, key);
//        System.out.println(sessionValues);
        return sessionValues;
    }

    public static String getTokenValue(String token, String key) {
//        System.out.println(token);
        String sessionValues = JwtUtil.getTokenInfo(token, key);
        return sessionValues;
    }


    public static ReplyObj flushFailure() {
        return new ReplyObj().setCode(503).setMsg("数据异常");
    }

    public static Predicate getPredicates(List<Predicate> predicates, String isUnion, final CriteriaBuilder cb) {
        if (!predicates.isEmpty()) {//非空
            Predicate returnPredicate = null;
            if ("yes".equals(isUnion)) {//都是使用and的
                for (int i = 0; i < predicates.size(); i++) {
                    if (returnPredicate == null) {
                        returnPredicate = cb.and(predicates.get(i));
                    } else {
                        returnPredicate = cb.and(returnPredicate, predicates.get(i));
                    }
                }
            } else {
                for (int i = 0; i < predicates.size(); i++) {
                    if (returnPredicate == null) {
                        returnPredicate = cb.or(predicates.get(i));
                    } else {
                        returnPredicate = cb.or(returnPredicate, predicates.get(i));
                    }
                }
            }
            return returnPredicate;
        }
        return null;
    }

    public static <T> Page<T> toPage(IPage<T> iPage) {
        List<T> content = iPage.getRecords();
        long totalElements = iPage.getTotal();
        return new PageImpl<>(content, Pageable.unpaged(), totalElements);
    }

    public static Predicate getPredicates(List<Predicate> predicates, final CriteriaBuilder cb) {
        String isUnion = "yes";
        if (!predicates.isEmpty()) {//非空
            Predicate returnPredicate = null;
            if ("yes".equals(isUnion)) {//都是使用and的
                for (int i = 0; i < predicates.size(); i++) {
                    if (returnPredicate == null) {
                        returnPredicate = cb.and(predicates.get(i));
                    } else {
                        returnPredicate = cb.and(returnPredicate, predicates.get(i));
                    }
                }
            } else {
                for (int i = 0; i < predicates.size(); i++) {
                    if (returnPredicate == null) {
                        returnPredicate = cb.or(predicates.get(i));
                    } else {
                        returnPredicate = cb.or(returnPredicate, predicates.get(i));
                    }
                }
            }
            return returnPredicate;
        }
        return null;
    }

    public synchronized String nextWorkSheet(String title, Long serial) {

        if (this.dateFormat == null) {
            this.dateFormat = "yyMMdd";
        }
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(dateFormat);
        if (this.length <= 0 || this.length > 12) {
            this.length = 5;
        }
        String format = "";
        for (int i = 0; i < this.length; i++) {
            format += "0";
        }
        java.text.NumberFormat nf = new java.text.DecimalFormat(format);
        String id = title + sdf.format(new Date()) + nf.format(serial);
        return id;
    }


    private String preFix;

    private String dateFormat;

    private int length;

    public static boolean checkStr(Object obj) {
        if (obj == null) {
            return false;
        } else {
            return checkStr(obj.toString());
        }
    }

    /**
     * @param preFix the preFix to set
     */
    public void setPreFix(String preFix) {
        this.preFix = preFix;
    }

    /**
     * @param dateFormat the dateFormat to set
     */
    public void setDateFormat(String dateFormat) {
        this.dateFormat = dateFormat;
    }

    /**
     * @param length the length to set
     */
    public void setLength(int length) {
        this.length = length;
    }

    public static List<Map<String, Object>> getTree(Map<String, List<Map<String, Object>>> allNodeMap, String parentId) {
        List<Map<String, Object>> list = allNodeMap.get(parentId);
        List<Map<String, Object>> allTree = new ArrayList<>();
        list = allNodeMap.get(parentId);
        if (list != null && list.size() > 0) {
            for (Map<String, Object> item : list) {
                List<Map<String, Object>> children = null;
                if (allNodeMap.containsKey(item.get("id").toString())) {
                    children = getTree(allNodeMap, item.get("id").toString());
                }
                if (CollectionUtils.isNotEmpty(children)) {
                    item.put("children", children);
                }
                allTree.add(item);
            }
        }
        return allTree;
    }
}
